package com.iot.service.mqtt.service.retain;

import com.iot.service.mqtt.model.request.TlMqttPublishReq;
import com.iot.service.mqtt.service.StoreStrategy;
import com.iot.service.mqtt.service.topic.ITopicService;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;


/**
 * @Author: hszhou
 * @Date: 2025/1/8 14:17
 * @Description: 必须描述类做什么事情, 实现什么功能
 */
@Service
@ConditionalOnProperty(prefix = "mqtt", name = "store-strategy", havingValue = StoreStrategy.REDIS)
@RequiredArgsConstructor
public class RedisRetainServiceImpl implements IRetainService, ITopicService {

    private static final Logger logger = LoggerFactory.getLogger(RedisRetainServiceImpl.class);


    private final ReactiveRedisTemplate<String,Object> reactiveRedisTemplate;

    private final String RETAIN_TOPIC_PREFIX = "retain:";

    @Override
    public Mono<Boolean> save(String topic, TlMqttPublishReq req) {

     return reactiveRedisTemplate.opsForValue().set(RETAIN_TOPIC_PREFIX+topic, req);
    }

    @Override
    public Mono<TlMqttPublishReq> find(String topic) {

        return reactiveRedisTemplate.opsForValue().get(RETAIN_TOPIC_PREFIX+topic).cast(TlMqttPublishReq.class)
                .doOnError(Throwable::printStackTrace);

    }

    @Override
    public Mono<Boolean> clear(String topic) {
       return reactiveRedisTemplate.delete(RETAIN_TOPIC_PREFIX+topic)
               .map(e->e>0);
    }
}
